/**
 * 
 */
package com.appspot.myjsf2.data;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.appspot.myjsf2.data.entity.MyTestDataBean;

/**
 * @author andyz
 *
 */
public class TestDAO {
	
	EntityManager em = MyEMFactory.getTestInstance().createEntityManager();
	
	public void createTestData(MyTestDataBean testData){
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		try{
			em.persist(testData);
		}catch(Exception e){
			e.printStackTrace();
		}
		tx.commit();
		em.close();
	}
	
	public MyTestDataBean createTestData(String name, String content){
		MyTestDataBean testData = new MyTestDataBean();
		testData.setName(name);
		testData.setContent(content);
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		try{
			em.persist(testData);
		}catch(Exception e){
			e.printStackTrace();
		}
		tx.commit();
		em.close();
		return testData;
	}
	
	public MyTestDataBean getTestData(Long id){
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		MyTestDataBean testData = null;
		try{
	        Query query = em.createQuery("select myTestData from MyTestDataBean myTestData where myTestData.id = :id ");
    		query.setParameter("id", id);
    		testData = (MyTestDataBean) query.getSingleResult();

		}catch(Exception e){
			e.printStackTrace();
		}
		tx.commit();
		em.close();
		return testData;
		
	}
}
